var gridObj;

$(function() {
    //初始化分页
    gridObj = $.fn.bsgrid.init('reportTable', {
        url: '/staff/reportQuery',
        pageSize: 10,
        pageSizeSelect: true,
        pageSizeForGrid: [5, 10, 15, 20],
        displayBlankRows: false,
        stripeRows: true,
        rowHoverColor: true,
    });
});


//添加未通过和未审核日报的操作连接
function operate(record, rowIndex, colIndex, options) {
    var status = gridObj.getRecordIndexValue(record, 'status');
    if (status == '未通过' || status == '未审核') {
        return '<button type="button" class="btn btn-xs btn-primary s-w50" onclick="management.modifyReport(' + rowIndex + ');">修改</button>  ' +
            '<button type="button" class="btn btn-xs btn-primary s-w50" onclick="management.deleteReport(' + gridObj.getRecordIndexValue(record, 'id') + ');">删除</button>';

    } else {
        return '';
    }
}


//为未通过的状态增加红色
function mark(record, rowIndex, colIndex, options) {
    var status = gridObj.getRecordIndexValue(record, 'status');
    if (status == '未通过') {
        return '<span class="red">' + status + '</span>';
    } else {
        return status;
    }
}




var management = {
    init: function() {
        var self = this;
        $('#startDate,#endDate').datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 2,
            minView: 2,
            autoclose: true,
            language: 'zh-CN',
            todayBtn: true,
        });

        //查找user所负责的项目
        self.getProjectList('projectItem1', null);

        self.getProjectList('projectItem2', function(pid) {
            self.changeTask(pid, 0, function(tid) {
                self.changeTaskProgress(tid);
            });

            //为日报状态下拉框增加下拉选项
            self.changeReportStatus(0, 'reportStatus1', 0);
            self.changeReportStatus(pid, 'reportStatus2', 0);
        });


        self.addEvent();
        self.validate();
    },

    // 绑定事件
    addEvent: function() {
        var self = this;
        //搜索处的新增按钮
        $('#add').click(function() {
            //查找user所负责的项目
            self.getProjectList('projectItem2', function(pid) {
                self.changeTask(pid, 0, function(tid) {
                    self.changeTaskProgress(tid);
                });

                //为日报状态下拉框增加下拉选项
                self.changeReportStatus(pid, 'reportStatus2', 0);
            });
            self.showDialog();
        });

        //弹出框的确认按钮
        $('#confirmAdd').click(function() {
            if ($('#reportForm').valid()) {
                if (!Number($('#rid').val())) {
                    self.checkReportDate(function(data) {
                        if (data.result) {
                            //block.showMsg(data.result);
                            alert(data.result);
                            // self.closeDialog();
                        } else {
                            self.confirmAdd();
                        }
                    });
                } else {
                    self.confirmAdd();
                }
            }
        });

        //弹出窗口的x
        $('#close1').click(function() {
            self.closeDialog();
        });

        //弹出窗的关闭按钮
        $('#close2').click(function() {
            self.closeDialog();
        });

        //搜索处的查询按钮
        $('#search').click(function() {
            self.search();
        });

        //当添加的时候，项目改变，任务的下拉框相应改变
        $('#projectItem2').change(function() {
            var pid = $('#projectItem2').val();
            self.changeTask(pid, 0, function(tid) {
                self.changeTaskProgress(tid);
            });
            self.changeReportStatus(pid, 'reportStatus2', 0);
        });

        //当任务改变时，进度相应改变
        $('#task').change(function() {
            self.changeTaskProgress($('#task').val());
        });
    },

    //显示弹出框
    showDialog: function() {
        $('#dialog').modal('show');
        $('#date').datetimepicker({
            format: 'yyyy-mm-dd',
            startView: 2,
            minView: 2,
            autoclose: true,
            language: 'zh-CN',
            todayBtn: true,
        });
    },

    //关闭弹出框并清空表单
    closeDialog: function() {
        $('#dialog').modal('hide');
        //清空表单
        $('#dialog form')[0].reset();
        $('#rid').val(0);
        $('#reportForm .error').text('');
    },

    //获取当前用户的下拉列表
    getProjectList: function(id, cb) {
        $.ajax({
            url: '/staff/queryProject',
            type: 'POST',
            success: function(data) {
                if (id === 'projectItem2')
                    $('#' + id).empty();
                $.each(data, function(index, value) {
                    $('#' + id).append('<option value="' + value.id + '">' + value.name + '</option>');
                });

                if (cb) {
                    cb($('#projectItem2').val());
                }
            },
            error: function(data) {}
        });
    },

    /**
     * 随着点击的项目改变，改变任务的下拉选项
     * @param pid 项目id
     * @param tid 任务id，如果为0则不选中
     */
    changeTask: function(pid, tid, cb) {
        $.ajax({
            type: 'POST',
            url: '/staff/queryUserProjectTask',
            data: {
                pid: pid
            },
            success: function(data) {
                $('#task').empty();
                //alert(JSON.stringify(data));
                $.each(data, function(index, value) {

                    $('#task').append('<option value="' + value.id + '">' + value.taskname + '</option>');
                });
                if (tid != 0)
                    $('#task').val(tid);

                if (cb) {
                    cb($('#task').val());
                }
            },
            error: function(data) {
                alert('出错了');
            },

        });
    },

    /**
     * 根据项目类型改变日报任务的状态
     * @param  {[int]} pid 项目id
     * @param  {[string]} id  控件的id
     * @param  {[int]} rsid 项目状态的id
     */
    changeReportStatus: function(pid, id, rsid) {
        //显示当前项目下日报的类型
        $.ajax({
            url: '/staff/queryReportStatus',
            data: {
                pid: pid
            },
            type: 'POST',
            success: function(data) {
                if (id === 'reportStatus2')
                    $('#' + id).empty();
                $.each(data, function(index, value) {
                    $('#' + id).append('<option value="' + value.id + '">' + value.name + '</option>');
                });
                if (rsid != 0)
                    $('#' + id).val(rsid);
            },
            error: function(data) {}
        });
    },

    //随任务获取进度
    changeTaskProgress: function(tid) {
        $.ajax({
            type: 'POST',
            url: '/staff/changeTaskProgress',
            data: {
                tid: tid
            },
            success: function(data) {
                //alert(JSON.stringify(data[0]));

                $('#progress').val(data[0].progress);
            },
            error: function(data) {
                alert('出错了');
            },
        });
    },

    //点击搜索按钮后触发的事件
    search: function() {
        var params = {
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val(),
            status: $('#searchStatus').val(),
            pid: $('#projectItem1').val(),
            tdescription: $('#tdescription').val(),
            rsid: $('#reportStatus1').val()
        };

        gridObj.search(params);
    },

    //删除日报功能
    deleteReport: function(rid) {
        if (confirm('确认删除？')) {
            $.ajax({
                type: 'POST',
                url: '/staff/deleteReport',
                data: {
                    rid: rid
                },
                success: function() {
                    block.showMsg('删除成功');
                    //alert('删除成功');
                    //刷新
                    gridObj.refreshPage();
                },
                error: function(data) {
                    alert('出错了');
                },
            });
        }
    },

    //修改日报功能
    modifyReport: function(rowIndex) {
        management.showDialog();
        var report = gridObj.getRecord(rowIndex);
        //alert(JSON.stringify(report));
        $('#date').val(report.date);
        $('#projectItem2').val(report.pid);
        $('#all_time').val(report.all_time);
        $('#over_time').val(report.over_time);
        $('#content').val(report.content);
        $('#progress').val(report.progress);
        $('#projectItem2').val(report.pid);
        $('#rid').val(report.id);
        //$('#task').val(report.tid);
        management.changeTask(report.pid, report.tid);
        management.changeReportStatus(report.pid, 'reportStatus2', report.rsid);
    },

    //弹出框的确认按钮
    confirmAdd: function() {

        var data = {
            id: $('#rid').val(),
            date: $('#date').val(),
            tid: $('#task').val(),
            all_time: $('#all_time').val(),
            over_time: $('#over_time').val(),
            content: $('#content').val(),
            rsid: $('#reportStatus2').val(),
            status: '未审核',
            progress: $('#progress').val()
        };

        //alert(JSON.stringify(data));
        $.ajax({
            url: '/staff/saveReport',
            type: 'POST',
            data: data,
            success: function(data) {
                management.closeDialog();
                //刷新
                gridObj.refreshPage();
            },

        });
    },

    //检查同一天有没有多发日报
    checkReportDate: function(cb) {
        $.ajax({
            url: '/staff/checkReportDate',
            type: 'POST',
            data: {
                date: $('#date').val(),
                tid:$('#task').val()
            },
            success: function(data) {
                //alert(JSON.stringify(data));
                if (cb) {
                    cb(data);
                }
            },
        });
    },

    /* 表单验证 */
    validate: function() {
        $.validator.addMethod('isSmaller', function(value, element) {
            var allTime = $('#all_time').val();
            return this.optional(element) || (value < allTime);
        }, '加班工作量必须小于有效工作量');

        $('#reportForm').validate({
            rules: {
                date: {
                    required: true,
                    date: true
                },
                projectItem2: 'required',
                task: 'required',
                progress: {
                    required: true,
                    range:[0, 100]
                },
                all_time: {
                    required: true,
                    number: true
                },
                over_time: {
                    number: true,
                    isSmaller: true
                },
                content: 'required',
            },
            messages: {
                date:{
                    required:'请选择日期',
                    date: '请正确填写日期'
                },
                projectItem2: '请选择项目',
                task: '请选择任务',
                progress: {
                    required: '请正确填写进度',
                    range:'进度范围为 0-100'
                },
                all_time: {
                    required: '请填写工作量',
                    number:'请正确填写工作量'
                },
                over_time: {
                    number:'请正确填写工作量',
                },
                content: '请填写日报内容',

            }
        });
    },


};
management.init();
